package com.lanou3g.demo.controller.roleinfo;

import com.lanou3g.demo.common.ResultWrapper;
import com.lanou3g.demo.entity.RoleInfo;
import com.lanou3g.demo.entity.ex.RoleWithModule;
import com.lanou3g.demo.service.roleInfo.IRoleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 调节器:处理service分发的请求
 */
@Controller
@RequestMapping("/role")
public class RoleInfoController {

    @Autowired
    private IRoleInfoService roleInfoService;

    /**
     * 查询所有的角色的名字的集合
     * @RequestMapping 发送到前端处理请求的方法
     * @return 返回的方法
     */
    @RequestMapping("/findAllRole")
    @ResponseBody
    public List<RoleInfo> findAll() {
        return roleInfoService.findAllRole();
    }


    /**
     * @return 查询某个角色和某个角色能进行操作的模块的信息
     */
    @RequestMapping("/findRoleWithModule")
    @ResponseBody
    public ResultWrapper findRoleWithModule(@RequestParam(defaultValue = "1") int page,
                                            @RequestParam(defaultValue = "3") int count) {

        List<RoleWithModule> roleWithModuleList = roleInfoService.findRoleWithModule(page, count);
        int totalCount = roleInfoService.roleQuantity();
        return ResultWrapper.success(totalCount, roleWithModuleList);
    }


    /**
     * 根据角色的id查询角色的信息
     */
    @RequestMapping("/findOneRole")
    @ResponseBody
    public RoleInfo findOneRole(Integer roleId) {

        return roleInfoService.findRoleById(roleId);
    }


    /**
     * 添加一个角色
     *
     * @param roleModule
     * @return
     */

    @RequestMapping("/addRole")
    public String addRole(@Validated RoleWithModule roleModule) {

        System.out.println("Controller层:" + roleModule);

        roleInfoService.addOneRole(roleModule.getRoleName(), roleModule.getAllModule());


        return "redirect:/role/role_list.html";
    }


    /**
     * 根据角色的Id删除一个角色和这个角色多对应的能操作的模块
     *
     * @param roleId
     */
    @RequestMapping(value = "/delRole", method = RequestMethod.POST)
    public void delRole(Integer roleId) {
        roleInfoService.delRoleWithModule(roleId);
    }

    /**
     * 修改一个角色的信息
     */

    @RequestMapping(value = "/updRole", method = RequestMethod.POST)
    public String updRole(@Validated RoleWithModule roleWithModule) {
            roleInfoService.udpRoleWithModule(roleWithModule);
        return "redirect:/role/role_list.html";
    }


}
